#!/bin/bash

# Source the platform_utils script
source "$(dirname "$0")/platform_utils" > /dev/null 2>&1

# Restrict command to sudo users
if [ "$EUID" -ne 0 ] ; then
  echo "Root priveleges are needed for this operation"
  exit 1
fi

PLATFORM="$(sonic-cfggen -d -v DEVICE_METADATA.localhost.platform)"
PLATFORM_ENV_CONF_FILE=/usr/share/sonic/device/$PLATFORM/platform_env.conf
if [ -f $PLATFORM_ENV_CONF_FILE ]; then
  source $PLATFORM_ENV_CONF_FILE
fi

if [ -f /etc/sonic/chassisdb.conf ] && [ "$SMARTSWITCH" = false ] && [[ $disaggregated_chassis -ne 1 ]]; then
  CHASSIS_TSA_STATE_UPDATE="CHASSIS_APP_DB HMSET "BGP_DEVICE_GLOBAL\|STATE" tsa_enabled "true""
  CONFIG_DB_TSA_STATE_UPDATE='{"BGP_DEVICE_GLOBAL":{"STATE":{"tsa_enabled": "true"}}}'
  current_tsa_state="$(sonic-cfggen -d -v BGP_DEVICE_GLOBAL.STATE.tsa_enabled)"
  if [[ $current_tsa_state  == true ]]; then
    echo "Chassis is already in Maintenance"
    logger -t TSA -p user.info "Chassis is already in Maintenance"
  else
    sonic-db-cli $CHASSIS_TSA_STATE_UPDATE
    sonic-cfggen -a "$CONFIG_DB_TSA_STATE_UPDATE" -w
    echo "Chassis Mode: Normal -> Maintenance"
    logger -t TSA -p user.info "Chassis Mode: Normal -> Maintenance"
  fi
  echo "Please execute 'sudo config save' to preserve System mode in Maintenance after reboot\
  or config reload on all linecards"
  exit 0
fi
# toggle the mux to standby if dualtor and any mux active
if
[[ "$(sonic-cfggen -d -v DEVICE_METADATA.localhost.subtype | tr '[:upper:]' '[:lower:]')" == *"dualtor"* ]] &&
[[ $(show mux status | grep active | wc -l) > 0 ]];
then
  logger -t TSA -p user.info "Toggle all mux mode to standby"
  sudo config mux mode standby all
fi

if [ -z "$STARTED_BY_TSA_TSB_SERVICE" ]; then
  service='startup_tsa_tsb.service'
  if [[ $(/bin/systemctl show $service --property ActiveState  --value) == "active" ]] && \
     [[ $(/bin/systemctl show $service --property SubState  --value) == "running" ]]; then
      echo "Stopping $service before configuring TSA"
      systemctl stop $service
      if sonic-db-cli STATE_DB HDEL "ALL_SERVICE_STATUS|tsa_tsb_service" "running" >/dev/null; then
        echo "Successfully removed TSA-TSB service flag."
      else
        echo "Failed to remove TSA-TSB service flag!" >&2
      fi
  fi
fi

/usr/bin/TS TSA
echo "Please execute 'sudo config save' to preserve System mode in Maintenance after reboot or config reload"

subtype=`sonic-db-cli CONFIG_DB hget 'DEVICE_METADATA|localhost' 'subtype'`
if [[ $subtype == *"UpstreamLC"* || $subtype == *"DownstreamLC"* ]] ; then
  echo -e "\nWARNING: Please execute 'TSA' on Supervisor or on all other linecards of the chassis to fully isolate the chassis"
fi